package com.cowin.inf.service.impl;

import com.cowin.inf.dao.KyDeviceStateMapper;
import com.cowin.inf.model.KyDeviceState;
import com.cowin.inf.model.KyDeviceStateInfo;
import com.cowin.inf.model.vo.KyDeviceStateVo;
import com.cowin.inf.service.KyDeviceStateService;
import com.cowin.base.AbstractServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


/**
 * Created by  on 2020/04/10.
 *
 * @author CodeGenerator
 */
@Slf4j
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class KyDeviceStateServiceImpl extends AbstractServiceImpl<KyDeviceState> implements KyDeviceStateService {

    @Resource
    private KyDeviceStateMapper kyDeviceStateMapper;
    @Resource
    KyDeviceStateInfoServiceImpl kyDeviceStateInfoService;

    @Override
    public int save(KyDeviceState model) {
        KyDeviceState kyDeviceState = kyDeviceStateMapper.selectByPrimaryKey(model);
        if (kyDeviceState != null) {
            if ("2001".equals(model.getFaultCode())) {
                log.info(model.getDeviceId() + "==心跳接口");
                return kyDeviceStateMapper.updateHeartbeatTime(model.getDeviceId());
            } else {
                if (!kyDeviceState.getFaultCode().equals(model.getFaultCode())) {
                    KyDeviceStateInfo kyDeviceStateInfo = new KyDeviceStateInfo();
                    kyDeviceStateInfo.setDeviceId(kyDeviceState.getDeviceId() + "");
                    kyDeviceStateInfo.setFaultCode(kyDeviceState.getFaultCode());
                    kyDeviceStateInfo.setStartTime(kyDeviceState.getNodeTime());
                    kyDeviceStateInfo.setEndTime(model.getNodeTime());
                    kyDeviceStateInfo.setDuration(Integer.parseInt((model.getNodeTime().getTime() - kyDeviceState.getNodeTime().getTime()) / 60000 + ""));
                    kyDeviceStateInfo.setBreakReason(kyDeviceState.getBreakReason());
                    kyDeviceStateInfo.setCreateTime(new Date());
                    kyDeviceStateInfoService.save(kyDeviceStateInfo);
                }
                model.setHeartbeatTime(new Date());
                return kyDeviceStateMapper.updateByPrimaryKeySelective(model);
            }
        } else {
            return super.save(model);
        }

    }

    @Override
    public List<KyDeviceStateVo> pmcMonitor(String workShopNo) {
       return kyDeviceStateMapper.pmcMonitor(workShopNo);
    }
}
